﻿#include "tcpassistant.h"
#include "ui_tcpassistant.h"

#include <QIntValidator>
#include <QHostInfo>
#include "myserver.h"
#include <QMessageBox>
#include "mysocket.h"



TcpAssistant::TcpAssistant(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TcpAssistant)
{
    ui->setupUi(this);
    m_tcpSocket=nullptr;
    //信息收发文本框高度3：1
    ui->splitter_3->setStretchFactor(0, 3);
    ui->splitter_3->setStretchFactor(1, 1);
    //设置端口输入校验
    ui->lineEdit_clientRemotePort->setValidator(new QIntValidator(0,65535));
    //ip校验正则
    QRegExp regExpIP("((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[\\.]){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])");

    //显示本地ip
    QString localip = this->sockethelper->Get_LocalIp();

    ui->lineEdit_clientRemoteIP->setText(localip);

    qDebug()<<"UI线程ID:"<<QThread::currentThreadId();
}

TcpAssistant::~TcpAssistant()
{
    if(m_tcpSocket!=nullptr)
    {
        m_tcpSocket->abort();
        delete m_tcpSocket;
    }
    delete ui;
}


//tcp客户端读取数据
void TcpAssistant::ClinetReadData()
{
    QByteArray ba = m_tcpSocket->readAll();
    QString data;
    //hex
    if(ui->chk_clientRecHex ->isChecked())
    {
        this->m_tcpServer->sockethelper->ByteToHexString(data,ba);
    }
    else//普通字符串
    {
        data=QString::fromLocal8Bit(ba);
    }
    //显示
    ui->text_clientRec->insertPlainText(data);
    ui->text_clientRec->moveCursor(QTextCursor::End);
}

//tcp客户端发生错误
void TcpAssistant::ClientReadError(QAbstractSocket::SocketError)
{
    QString err=QString("发生错误:%1").arg(m_tcpSocket->errorString());
    ui->text_clientRec->appendPlainText(err);
    m_tcpSocket->disconnect();//断开所有信号
    m_tcpSocket->abort();//终止socket连接
    m_tcpSocket->deleteLater();//释放
    m_tcpSocket=nullptr;
    //更新UI
    ui->text_clientRec->appendPlainText("已断开服务器"+QString("[%1：%2]\r\n").arg(ui->lineEdit_clientRemoteIP->text()).arg(ui->lineEdit_clientRemotePort->text()));
    ui->btn_clientConnect->setText("连接");
    ui->btn_clientConnect->setIcon(QIcon(":/Resource/Img/stop36x36.png"));
    ui->lineEdit_clientRemoteIP->setEnabled(true);
    ui->lineEdit_clientRemotePort->setEnabled(true);

}

//tcp客户端连接/断开
void TcpAssistant::on_btn_clientConnect_clicked()
{
    if(m_tcpSocket == nullptr)
    {
        //获取本地端口
        bool ok;
        quint16 port=ui->lineEdit_clientRemotePort->text().toUShort(&ok);
        if(!ok)
        {
            QMessageBox::warning(this,"错误","远程端口设置有误，请重新输入");
            return;
        }
        //获取本地Ip
        QHostAddress ip(ui->lineEdit_clientRemoteIP->text());
        ip.toIPv4Address(&ok);
        if(!ok)
        {
            QMessageBox::warning(this,"错误","远程ip设置有误，请重新输入");
            return;
        }

        this->m_tcpSocket=new QTcpSocket(this);
        m_tcpSocket->connectToHost(ip,port);
        connect(m_tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(ClientReadError(QAbstractSocket::SocketError)));
        //等待连接
        if (m_tcpSocket->waitForConnected(1000))
        {
            connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(ClinetReadData()));

            //更新UI
            ui->text_clientRec->appendPlainText("已连接服务器"+QString("[%1：%2]\r\n").arg(ui->lineEdit_clientRemoteIP->text()).arg(ui->lineEdit_clientRemotePort->text()));
            ui->btn_clientConnect->setText("断开");
            ui->btn_clientConnect->setIcon(QIcon(":/Resource/Img/stop36x36.png"));
            ui->lineEdit_clientRemoteIP->setEnabled(false);
            ui->lineEdit_clientRemotePort->setEnabled(false);
        }
        else//连接失败
        {
            m_tcpSocket->disconnect();
            m_tcpSocket->deleteLater();
            m_tcpSocket=nullptr;
            ui->text_clientRec->appendPlainText("连接失败"+QString("[%1：%2]\r\n").arg(ui->lineEdit_clientRemoteIP->text()).arg(ui->lineEdit_clientRemotePort->text()));
        }

    }
    else
    {
        m_tcpSocket->disconnect();//断开信号槽
        m_tcpSocket->abort();//终止
        m_tcpSocket->deleteLater();//释放
        m_tcpSocket=nullptr;
        //更新UI
        ui->text_clientRec->appendPlainText("已断开服务器"+QString("[%1：%2]\r\n").arg(ui->lineEdit_clientRemoteIP->text()).arg(ui->lineEdit_clientRemotePort->text()));
        ui->btn_clientConnect->setText("连接");
        ui->btn_clientConnect->setIcon(QIcon(":/Resource/Img/start36x36.png"));
        ui->lineEdit_clientRemoteIP->setEnabled(true);
        ui->lineEdit_clientRemotePort->setEnabled(true);
    }
}

//清除tcp客户端接收
void TcpAssistant::on_btn_clientClearRec_clicked()
{
    ui->text_clientRec->clear();
}

//清除tcp客户端发送
void TcpAssistant::on_btn_clientClearSend_clicked()
{
    ui->text_clientSend->clear();
}

//点击tcp客户端发送
void TcpAssistant::on_btn_clientSend_clicked()
{
    QByteArray byteArray;
    QString data=ui->text_clientSend->toPlainText();
    //Hex发送
    if(ui->chk_clientSendHex->isChecked())
    {
        //hex字符串转字节
//        if(!HexStringToByte(data,byteArray))
//        {
//            QMessageBox::information(this,"提示","输入的十六进制字符串有误，请重新输入");
//            return;
//        }
    }
    //普通字符串发送
    else
    {
        byteArray= data.toLocal8Bit();
    }
    m_tcpSocket->write(byteArray);
}
